import dayjs from "dayjs";
import editForm from "../form.vue";
import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import { usePublicHooks } from "../../hooks";
import { transformI18n } from "@/plugins/i18n";
import { addDialog } from "@/components/ReDialog";
import type { FormItemProps } from "../utils/types";
import type { PaginationProps } from "@pureadmin/table";
import { getKeyList, deviceDetection } from "@pureadmin/utils";
import { type Ref, reactive, ref, onMounted, h, toRaw, watch } from "vue";
import {
  queryRoles,
  createRole as create,
  updateRole as update,
  batchDeleteRole as batchDelete,
  setRoleEnabledStatus,
  getRoleMenusById,
  assignMenusToRole,
  getRoleMenus
} from "@/swagger/api/role";
import { GridifyQueryBuilder, ConditionalOperator as op } from "gridify-client";

export function useRole(treeRef: Ref) {
  const form = reactive({
    name: "",
    code: "",
    enabled: ""
  });
  const curRow = ref();
  const formRef = ref();
  const dataList = ref([]);
  const treeIds = ref([]);
  const treeData = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const isLinkage = ref(true);
  const treeSearchValue = ref();
  const switchLoadMap = ref({});
  const isExpandAll = ref(false);
  const isSelectAll = ref(false);
  const { switchStyle } = usePublicHooks();
  const treeProps = {
    value: "id",
    label: "title",
    children: "children"
  };
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "角色编号",
      prop: "id",
      formatter: ({ id }) => {
        const str = String(id || '');
        return str.length <= 13 ? str : str.slice(-12);
      }
    },
    {
      label: "角色名称",
      prop: "name"
    },
    {
      label: "角色标识",
      prop: "code"
    },
    {
      label: "状态",
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.enabled}
          active-value={true}
          inactive-value={false}
          active-text="已启用"
          inactive-text="已停用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      ),
      minWidth: 90
    },
    {
      label: "备注",
      prop: "description",
      minWidth: 160
    },
    {
      label: "创建时间",
      prop: "created",
      minWidth: 160,
      formatter: ({ created }) =>
        dayjs(created).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation"
    }
  ];

  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${row.enabled === false ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${row.name
      }</strong>吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        setTimeout(async () => {
          switchLoadMap.value[index] = Object.assign(
            {},
            switchLoadMap.value[index],
            {
              loading: false
            }
          );
          await setRoleEnabledStatus({ id: row.id }, { id: row.id, enabled: row.enabled });
          message(`已${row.enabled === false ? "停用" : "启用"}${row.name}`, {
            type: "success"
          });
        }, 300);
      })
      .catch(() => {
        row.enabled === false ? (row.enabled = true) : (row.enabled = false);
      });
  }

  async function handleDelete(row) {
    await batchDelete({ roleIds: [row.id] })
    message(`您删除了角色名称为${row.name}的这条数据`, { type: "success" });
    onSearch();
  }

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
    onSearch();
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    onSearch();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
    onSearch();
  }

  async function onSearch() {
    loading.value = true;

    const query = new GridifyQueryBuilder()
      .setPage(pagination.currentPage)
      .setPageSize(pagination.pageSize)
      .addOrderBy("sort", true)
      .addCondition("name", op.Contains, form.name);

    if (form.code) {
      query.and().addCondition("code", op.Contains, form.code);
    }
    if (form.enabled !== "" && form.enabled !== undefined) {
      query.and().addCondition("enabled", op.Equal, form.enabled);
    }

    const queryBuilder = query.build() as any;
    const { data } = await queryRoles(queryBuilder) as any;

    dataList.value = data.items;
    pagination.total = data.totalItems;
    pagination.currentPage = data.currentPage;

    loading.value = false;
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}角色`,
      props: {
        formInline: {
          id: row?.id ?? "",
          name: row?.name ?? "",
          code: row?.code ?? "",
          description: row?.description ?? "",
          sort: row?.sort ?? 0,
          enabled: row?.enabled ?? true
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了角色名称为${curData.name}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            console.log("curData", curData);
            // 表单规则校验通过
            if (title === "新增") {
              await create(curData);
              chores();
            } else {
              await update({ id: curData.id }, curData);
              chores();
            }
          }
        });
      }
    });
  }

  const getNodesWithChildren = (tree: any[]): string[] => {
    const result: string[] = [];

    const traverse = (nodes: any[]) => {
      nodes.forEach(node => {
        if (node.children && node.children.length > 0) {
          result.push(node.id);          // 保存当前有子节点的节点 ID
          traverse(node.children);       // 递归子节点
        }
      });
    };

    traverse(tree);
    return result;
  };

  /** 菜单权限 */
  async function handleMenu(row?: any) {
    const { id } = row;
    if (id) {
      curRow.value = row;
      isShow.value = true;
      const { data } = await getRoleMenusById({ id: id }, { roleId: id });
      /* @ts-ignore */
      const ids = data.map(item => item.id);
      const nodesWithChildrenIds = getNodesWithChildren(treeData.value);
      const leafIds = ids.filter(id => !nodesWithChildrenIds.includes(id));//去掉父节点/避免选中父节点后勾选全部/导致显示不正确
      treeRef.value.setCheckedKeys(leafIds);
    } else {
      curRow.value = null;
      isShow.value = false;
    }
  }

  /** 高亮当前权限选中行 */
  function rowStyle({ row: { id } }) {
    return {
      cursor: "pointer",
      background: id === curRow.value?.id ? "var(--el-fill-color-light)" : ""
    };
  }

  /** 菜单权限-保存 */
  async function handleSave() {
    const { id, name } = curRow.value;

    const checkedNodes = treeRef.value.getHalfCheckedNodes().map(node => node.id);//获取半选的
    const checkedKeys = treeRef.value.getCheckedKeys();//获取全选的
    await assignMenusToRole({ id: id }, { roleId: id, menuIds: checkedNodes.concat(checkedKeys) });

    message(`角色名称为${name}的菜单权限修改成功`, {
      type: "success"
    });
  }

  /** 数据权限 可自行开发 */
  // function handleDatabase() {}

  const onQueryChanged = (query: string) => {
    treeRef.value!.filter(query);
  };

  const filterMethod = (query: string, node) => {
    return transformI18n(node.title)!.includes(query);
  };

  onMounted(async () => {
    onSearch();
    const { data } = await getRoleMenus();
    treeIds.value = getKeyList(data, "id");
    /* @ts-ignore */
    treeData.value = handleTree(data);
  });

  watch(isExpandAll, val => {
    val
      ? treeRef.value.setExpandedKeys(treeIds.value)
      : treeRef.value.setExpandedKeys([]);
  });

  watch(isSelectAll, val => {
    val
      ? treeRef.value.setCheckedKeys(treeIds.value)
      : treeRef.value.setCheckedKeys([]);
  });

  return {
    form,
    isShow,
    curRow,
    loading,
    columns,
    rowStyle,
    dataList,
    treeData,
    treeProps,
    isLinkage,
    pagination,
    isExpandAll,
    isSelectAll,
    treeSearchValue,
    // buttonClass,
    onSearch,
    resetForm,
    openDialog,
    handleMenu,
    handleSave,
    handleDelete,
    filterMethod,
    transformI18n,
    onQueryChanged,
    // handleDatabase,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
